﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace LeMigue.Scrum.TfsScrumV1.Utils
{
    public class TfsQuery
    {

        protected StringBuilder _query;

        protected StringBuilder _where = null;
        protected IList<string> _order = null;

        protected Hashtable _hashtable = new Hashtable();

        protected TfsQuery(TfsTable from, WorkItemFields[] fields)
        {
            _query = new StringBuilder("SELECT ")
                .Append(String.Join(",", fields.Select(f => f.ToString())))
                .Append(" FROM ").Append(from.ToString());
            
        }

        public TfsQuery AppendWhere(string value)
        {
            if (_where == null)
                _where = new StringBuilder();

            _where.Append(value);

            return this;
        }

        public TfsQuery AppendWhere(WorkItemFields column, string operador, object value)
        {
            if (_where == null)
                _where = new StringBuilder();

            if (!_hashtable.ContainsKey(column.Key))
                _hashtable.Add(column.Key, value);

            _where.Append(String.Format(" {0} {1} @{2} ", column.ToString(), operador, column.Key));

            return this;
        }

        public TfsQuery AppendOrder(WorkItemFields column, bool ascendent = true)
        {
            if (_order == null)
                _order = new List<string>();

            _order.Add(String.Format(" {0} {1} ", column.ToString(), (ascendent?"":"DESC")));


            return this;
        }
        public TfsQuery AppendOrder(string order)
        {
            if (_order == null)
                _order = new List<string>();

            _order.Add(order);


            return this;
        }

        public Hashtable Hashtable
        {
            get { return _hashtable; }
        }

        public override string ToString()
        {
            StringBuilder query = new StringBuilder(_query.ToString());

            if (_where != null && _where.Length > 0)
                query.Append(" WHERE ").Append(_where.ToString());

            if (_order != null && _order.Count > 0)
                query.Append(" ORDER BY ").Append(String.Join(",", _order));

            return query.ToString();
        }

    }
}
